package com.five.student.tool;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        String uri = request.getRequestURI();

        // 登录页、静态资源、退出接口放行
        if (uri.contains("/login") || uri.contains("/static/") || uri.contains("/logout")) {
            return true;
        }

        if (user == null) {
            response.sendRedirect("/login");
            return false;
        }

        return true;
    }
}
